<template>
  <template v-if="auth !== 'hide'">
    <template v-if="showLabel">
      <van-field
          @blur="blur"
          @focus="focus"
          :id="id"
          v-if="auth === 'edit'"
          :required="required"
          :label="fieldConfig?.label"
          autosize v-model="innerValue"
          clearable
          :placeholder="fieldConfig?.placeholder"/>
      <van-cell :id="id" v-else :title="fieldConfig?.label">
        <template #value>
          <div class="relation-link" @click.stop="() => emits('openRelationForm')" v-if="isLink">
            {{ innerValue }}
          </div>
          <template v-else>
            {{ innerValue }}
          </template>
        </template>
      </van-cell>
    </template>
    <template v-else>
      <HInput
          :id="id"
          allowClear
          v-if="auth === 'edit'"
          v-model="innerValue"
          :required="required"
          :placeholder="fieldConfig?.placeholder" @blur="blur"
          @focus="focus"/>
      <template v-else>
        <span :id="id" class="common-link" @click.stop="() => emits('openRelationForm')" v-if="isLink">
          {{ innerValue }}
        </span>
        <template v-else>
          <span :id="id">{{ innerValue }}</span>
        </template>
      </template>
    </template>
  </template>
</template>
<script setup>
import {createProps} from '@/utils';
import {nextTick, shallowRef, watch} from 'vue';
import HInput from '@comp/FormEngine/HInput/HInput.vue';

const props = defineProps({
  showLabel: createProps(Boolean),
  id: createProps(String),
  value: createProps(String),
  fieldConfig: createProps(Object, () => undefined),
  required: createProps(Boolean),
  auth: createProps(String, 'edit'),
  rowIndex: createProps(Number),
  isLink: createProps(Boolean),
});
const emits = defineEmits(['update:value', 'openRelationForm']);
const tempValue = shallowRef();
const innerValue = shallowRef();
const focusing = shallowRef(false);

function focus() {
  // tempValue.value = innerValue.value
  focusing.value = true;
}

function blur() {
  focusing.value = false;
  // if (innerValue.value !== tempValue.value) {
  //   emits('update');
  // }
  if (innerValue.value !== props.value) {
    emits('update:value', innerValue.value);
    nextTick(() => {
      emits('update');
    });
  }
}

watch(() => props.value, (newValue) => {
  nextTick(() => {
    if (focusing.value) {

    } else {
      innerValue.value = props.value;
    }
  });
}, {
  immediate: true,
});

// const innerValue = computed({
//   get() {
//     return props.value;
//   },
//   set(value) {
//     emits('update:value', value);
//   }
// });


// watch(() => innerValue.value, (newValue) => {
//   nextTick(() => {
//     if (focusing.value) return
//     emits('update');
//   })
// }, {
//   immediate: false,
// })
</script>